package com.heima.wemedia.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
        if (StrUtil.isNotBlank(dto.getName()) && StrUtil.isNotBlank(dto.getPassword())) {
            WmUser one = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
            if (ObjectUtil.isEmpty(one)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在,请注册");
            }

            String hashpd = one.getPassword();
            String password = dto.getPassword();
            boolean checkpw = BCrypt.checkpw(password, hashpd);
            if (!checkpw) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户密码,请重新输入");
            }
            //返回数据
            String token = AppJwtUtil.getToken(one.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            one.setPhone("");
            one.setPassword("");
            map.put("user",one);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在,请注册");
    }
}